package com.hj.common.config;

import com.hj.common.constant.RabbitAttribute;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    //声明交换机
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(RabbitAttribute.DIRECT_EXCHANGE);
    }

    //TODO : 短信队列
    //声明队列
    @Bean
    public Queue smsQueue(){
        return QueueBuilder.durable(RabbitAttribute.SMS_QUEUE).build();
    }

    //将队列绑定到交换机
    @Bean
    public Binding smsBinding(){
        return BindingBuilder.bind(smsQueue()).to(directExchange()).with(RabbitAttribute.SEND_SMS_ROUTINGKEY);
    }

    //TODO : websocket发送消息
    //声明队列
    @Bean
    public Queue websocketQueue(){
        return QueueBuilder.durable(RabbitAttribute.WEBSOCKET_QUEUE).build();
    }

    //将队列绑定到交换机
    @Bean
    public Binding websocketBinding(){
        return BindingBuilder.bind(websocketQueue()).to(directExchange()).with(RabbitAttribute.SEND_WEBSOCKET_ROUTINGKEY);
    }

    //TODO : 延时队列Bean对象
    @Bean
    public Queue delayQueue() {
        Map args = new HashMap();
        //过期后自动把消息转到死信队列
        args.put("x-dead-letter-exchange",RabbitAttribute.DEAD_EXCHANGE);
        args.put("x-dead-letter-routing-key",RabbitAttribute.DEAD_ROUTINGKEY);
        args.put("x-message-ttl",30 * 60 * 1000);//设置过期时间为30分钟
        /**
         * 1 : 队列名称
         * 2 : true 设置队列为持久队列 在服务器重启会保留该队列
         * 3 : flase 设置队列非独占队列
         * 4 : flase 服务器不适应队列不会被删除
         * 5 : 声明队列参数
         */
        return new Queue(RabbitAttribute.DELAY_QUEUE, true,false,false,args);
    }

    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(directExchange()).with(RabbitAttribute.DELAY_ROUTINGKEY);
    }

    //TODO : 死信
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange(RabbitAttribute.DEAD_EXCHANGE);
    }

    @Bean
    public Queue deadQueue() {
        return new Queue(RabbitAttribute.DEAD_QUEUE, true); //队列持久
    }

    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(RabbitAttribute.DEAD_ROUTINGKEY);
    }
}
